package com.leetcode.string;

import java.util.ArrayList;
import java.util.List;

public class GroupAnagrams {
    public List<List<String>> groupAnagrams(String[] strs) {
        List<List<String>> resList = new ArrayList<>();
        int[][] matrix = new int[strs.length][26];
        for (int i = 0; i < strs.length; i++) {
            for (int j = 0; j < strs[i].length(); j++) {
                matrix[i][strs[i].charAt(j) - 'a']++;
            }
        }
        boolean[] isUsed = new boolean[strs.length];
        for (int i = 0; i < strs.length; i++) {
            if(isUsed[i]) {
                continue;
            }
            List<String> tmpList =  new ArrayList<>();
            tmpList.add(strs[i]);
            for (int j = i + 1; j < strs.length; j++) {
                if (!isUsed[j] && isEqual(matrix[i], matrix[j])) {
                    tmpList.add(strs[j]);
                    isUsed[j] = true;
                }
            }
            resList.add(new ArrayList<>(tmpList));
            isUsed[i] = true;
        }
        return resList;
    }

    private boolean isEqual(int[] arr1, int[] arr2) {
        for (int i = 0; i < arr1.length; i++) {
            if(arr1[i] != arr2[i]) {
                return false;
            }
        }
        return true;
    }
}
